function $ajax({ method = "GET", url }) {
  return new Promise(function (resolve, reject) {
    // 确定何时成功 何时失败
    let xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.addEventListener("readystatechange", () => {
      if (xhr.readyState !== 4) {
        // 如果 状态值 尚未变成4(未完成),则直接退出函数
        return;
      }
      // 如果请求成功,则 调用 resolve
      if (xhr.status == 200) {
        // 将响应体 通过 resolve 传递出去
        resolve(JSON.parse(xhr.response));
      } else {
        let errInfo = {
          msg: "请求失败",
          errUrl: url,
          status: xhr.status,
        };
        reject(errInfo);
      }
    });
    xhr.send();
  });
}

let preText = document.querySelector("#preText");
let loadSuccess = true;
let tip = document.querySelector(".tip");
let audio = document.querySelector("#song");
let btn = document.querySelector(".btn");
let dj = document.querySelector("#dj");
let op = document.querySelector("#opt");
let tp = document.querySelector(".tp");
let option = document.querySelector(".option");
let main = document.querySelector(".main");
let resGuess = document.querySelector("#res-guess");
let prizeImg = document.querySelector(".prize img");
let zc = document.querySelector(".zc");
let resul = document.querySelector("#resul");
let pop = document.querySelector("#pop");
var mySwiper;
console.log(zc);

// 预加载函数
function preloadFn(musicSrc) {
  // 预加载函数
  let preload = new createjs.LoadQueue(true);
  //注意加载音频文件需要调用如下代码行
  preload.installPlugin(createjs.SOUND);
  //为preloaded添加整个队列变化时展示的进度事件
  preload.addEventListener("progress", handleFileProgress);
  //为preloaded添加当队列完成全部加载后触发事件
  preload.addEventListener("complete", loadComplete);
  preload.addEventListener("error", loadErr);
  //设置最大并发连接数  最大值为10
  preload.setMaxConnections(10);
  preload.loadManifest(musicSrc);

  // 当整个队列变化时展示的进度事件的处理函数
  function handleFileProgress(event) {
    // console.log("进度改变",event);
    if (loadSuccess) {
      //preText.innerText = "Loading"+(event.loaded * 100).toFixed(2);
      preText.innerText = "Loading" + Math.ceil(event.loaded * 100) + "%";
    }
  }
  // 当加载失败时,触发的处理函数
  function loadErr() {
    loadSuccess = false;
    console.log("资源加载失败");
    // window.location.reload();
  }
  // 处理preload添加当队列完成全部加载后触发事件
  function loadComplete(event) {
    if (!loadSuccess) return;
    // console.log(event);
    let load = document.querySelector("#load");
    // 设置定时器，当全部加载完毕后让100%停留0.3秒，提高用户体验，不至于让用户感觉不到
    window.setTimeout(() => {
      load.style.transform = `translateX(-100%)`;
      // alert("全部完全加载完成!")
    }, 300);
  }

  tip.addEventListener("click", function () {
    load.style.transform = `translateX(-100%)`;
  });
}
// 获取音乐文件资源路径JONS
$ajax({ url: "./data/music.json" })
  .then((res) => {
    let sy = document.querySelector("#sy");
    // 取得随机30首音乐的资源
    let musicData = res
      .sort(() => {
        return Math.random() - 0.5;
      })
      .slice(0, 30);
    let musicSrc = musicData.map((e) => e.audio);
    // 进行预加载
    preloadFn(musicSrc);

    btn.addEventListener("click", function () {
      // sy.style.transform = `translate(-100%)`;
      sy.style.display = "none";
      console.log("点了");
      mySwiper = new Swiper(".swiper-container", {
        direction: "horizontal", // 垂直切换选项
        loop: true, // 循环模式选项
        autoplay: {
          delay: 10000,
          stopOnLastSlide: false,
          disableOnInteraction: true,
        },
        observer: true, // 开启观察模式,当 slide 或 swiper 变化时,重新实例化swiper
        observeSlideChildren: true,
        observerParents: true,
        initialSlide :0,
        effect : 'fade',
        on: {
          init: function () {
            swiperAnimateCache(this); //隐藏动画元素
            swiperAnimate(this); //初始化完成开始动画
          },
          slideChangeTransitionEnd: function () {
            swiperAnimate(this); //每个slide切换结束时也运行当前slide动画
           // this.slides.eq(this.activeIndex).find('.ani').removeClass('ani'); //动画只展现一次，去除ani类名
          },
        },
      });
    });
    return musicData;
  })
  .then((res) => {
    let opt = document.querySelectorAll(".option li p");
    let grade = 0; //计分
    let qusIdx = 0; //当前所在题数
    let onoff = true; //设置开关控制s
    btn.addEventListener("click", function () {
      reanderAndPlay(Symbol());
      var time = 59;
      var timer = setInterval(() => {
        dj.innerText = `${time}s`;
        time--;
        if (time == -1) {
          audio.pause();
          main.style.display = "none";
          option.style.display = "none";
          clearInterval(timer);
          resGuess.innerText = `猜中${grade}首`;
          switch (true) {
            case 0 <= grade && grade < 7:
              prizeImg.src = "./images/resul/qingt.png";
              break;
            case 6 < grade && grade < 13:
              prizeImg.src = "./images/resul/baiy.png";
              break;
            case 12 < grade && grade < 19:
              prizeImg.src = "../images/resul/huangj.png";
              break;
            case 18 < grade && grade < 25:
              prizeImg.src = "./images/resul/boj.png";
              break;
            case 24 < grade && garde < 31:
              prizeImg.src = "./images/resul/zuans.png";
              break;
          }
        }
        if (!time) {
          mySwiper.autoplay.stop();
        }
      }, 1000);
    });
    opt.forEach((el, idx) => {
      el.addEventListener("click", function () {
        if (onoff) {
          onoff = false;
          setTimeout(() => {
            tp.style.opacity = "0";
            onoff = true;
          }, 2000);
          if (qusIdx == res.length - 1) {
            console.log("游戏结束", grade);
            return;
          }
          if (idx == res[qusIdx].answer) {
            grade++;

            console.log("恭喜答对,+1", grade);
          }
          console.log("当前所在题数：", qusIdx);
          console.log("当前点击的为:", idx);
          reanderAndPlay();
        } else {
          tp.style.opacity = "1";
          console.log("请听2秒");
        }
      });
    });

    //封装播放
    function reanderAndPlay(isFirst) {
      isFirst || qusIdx++;
      audio.src = res[qusIdx].audio;
      audio.play();
      opt.forEach((el, idx) => {
        el.innerText = res[qusIdx].item[idx];
      });
    }
    console.log("当前题目数据", res[qusIdx].audio);
  })
  .catch((err) => {
    console.log(err);
  });

zc.addEventListener("click", function () {
  console.log("点击了");
  sy.style.display = "block";

  main.style.display = "block";
  option.style.display = "flex";
});
